# -*- coding:utf-8 -*-

from PyQt4 import QtGui, QtCore
from constants import *
from utils import *
from ssc_data import *

class SSCWidget(QtGui.QWidget):
    '''ssc emulator'''
    def __init__(self, ssc_type, parent = None):
        QtGui.QWidget.__init__(self, parent)

        self._ssc_type = ssc_type

        self._init_data()
        self._init_child()
        self._init_event()

        self._timer = QtCore.QTimer()
        self.connect(
            self._timer, 
            QtCore.SIGNAL("timeout()"), 
            self._on_timer
        )

    def _init_data(self):
        if self._ssc_type == SSC_CQ:
            self._history_url = CQ_RECORD_URL
        else:
            self._history_url = XJ_RECORD_URL

        self._running = False
        self._reset_data()

    def _reset_data(self):
        self._buy_list = []
        self._last_result = None
        self._cur_buy_data = None
        self._follow_times_list = [1,1,1,1,1]
        self._my_money = 0
        self._max_money = 0
        self._min_money = 0
        self._hit_buy_times = 0
        self._max_buy_times = 0
        self._hit_percent = 0.0
        self._round_max_pay = 0
        self._round_max = 0
        Utils.index = 0

    def _init_child(self):

        _int_validator = QtGui.QIntValidator(0, 99999999)

        self._grid = QtGui.QGridLayout()
        self._grid.setSpacing(20)
        self.setLayout(self._grid)

        hbox1 = QtGui.QHBoxLayout()
        self._grid.addLayout(hbox1, 0, 0)

        self._label_money = QtGui.QLabel("现有财富:")
        self._edit_money = QtGui.QLineEdit("0")
        self._edit_money.setDisabled(True)
        self._label_number_money = QtGui.QLabel("每注:")
        self._edit_number_money = QtGui.QLineEdit("10")
        self._edit_number_money.setValidator(_int_validator)
        self._cb_strategy = QtGui.QComboBox()
        self._cb_strategy.addItem("翻倍跟", STRAGERY_SQUARE)
        self._cb_strategy.addItem("线性跟", STRAGERY_LINE)
        hbox1.addWidget(self._label_money)
        hbox1.addWidget(self._edit_money)
        hbox1.addWidget(self._label_number_money)
        hbox1.addWidget(self._edit_number_money)
        hbox1.addWidget(self._cb_strategy)

        hbox2 = QtGui.QHBoxLayout()
        self._grid.addLayout(hbox2, 1, 0)
        self._label_condition = QtGui.QLabel("条件:")
        self._cb_condition = QtGui.QComboBox()
        self._cb_condition.addItem("正跟", ORDER_FOLLOW)
        self._cb_condition.addItem("反跟", REVERSE_FOLLOW)
        self._label_hit = QtGui.QLabel("连击次数:")
        self._edit_hit = QtGui.QLineEdit("3")
        self._edit_hit.setValidator(_int_validator)
        hbox2.addWidget(self._label_condition)
        hbox2.addWidget(self._cb_condition)
        hbox2.addWidget(self._label_hit)
        hbox2.addWidget(self._edit_hit)

        hbox4 = QtGui.QHBoxLayout()
        self._grid.addLayout(hbox4, 2, 0)
        self._label_record = QtGui.QLabel("记录:")
        self._button_reset = QtGui.QPushButton("重置")
        self._button_start = QtGui.QPushButton("开始")
        hbox4.addWidget(self._label_record)
        hbox4.addWidget(self._button_reset)
        hbox4.addWidget(self._button_start)

        self._table_summary = QtGui.QTableWidget(1, 5)
        self._table_summary.setHorizontalHeaderLabels(
            ["总期数", "最高", "最低", "命中率", "最大注"]
        )
        self._grid.addWidget(self._table_summary, 3, 0)
        self._table_item_max_round = QtGui.QTableWidgetItem()
        self._table_summary.setItem(0, 0, self._table_item_max_round)
        self._table_item_max = QtGui.QTableWidgetItem()
        self._table_summary.setItem(0, 1, self._table_item_max)
        self._table_item_min = QtGui.QTableWidgetItem()
        self._table_summary.setItem(0, 2, self._table_item_min)
        self._table_item_percent = QtGui.QTableWidgetItem()
        self._table_summary.setItem(0, 3, self._table_item_percent)
        self._table_item_round_max_pay = QtGui.QTableWidgetItem()
        self._table_summary.setItem(0, 4, self._table_item_round_max_pay)

        self._table_record = QtGui.QTableWidget(20, 4)
        self._table_record.setHorizontalHeaderLabels(
            ["期号", "投注", "结果", "命中"]
        )
        self._table_record.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
        self._table_record.setColumnWidth(1, 250)
        self._table_record.setColumnWidth(2, 100)
        self._grid.addWidget(self._table_record, 4, 0)
        
    def _init_event(self):
        self.connect(
            self._button_start, 
            QtCore.SIGNAL("clicked()"), 
            self._on_start
        )

        self.connect(
            self._button_reset,
            QtCore.SIGNAL("clicked()"),
            self._on_reset
        )

    def _on_timer(self):
        temp_results = Utils.catch_result(self._history_url)
        if temp_results is None:
            self._stop()
            return
        temp_result = temp_results[len(temp_results)-1]
        if self._last_result:
            #期号相同
            if temp_result.round == self._last_result.round:
                return
        
        self._last_result = temp_result

        is_catch = False

        if self._cur_buy_data and temp_result.round != self._cur_buy_data.pre_round:
            for i, r in enumerate(temp_results):
                if r.round == self._cur_buy_data.pre_round:
                    match = temp_results[i-1]
                    self._cur_buy_data.round = match.round
                    self._cur_buy_data.results = match.results
                    for j, b in enumerate(self._cur_buy_data.select_nums):
                        if len(b) == 0:
                            continue
                        self._max_buy_times += 1
                        if match.results[j] in b:
                            self._cur_buy_data.hits[j] = match.results[j]
                            self._my_money += self._cur_buy_data.pre_money_list[j]*AWARD_RATIO
                            if self._my_money > self._max_money:
                                self._max_money = self._my_money
                            self._follow_times_list[j] = 1
                            self._hit_buy_times += 1
                        else:
                            self._follow_times_list[j] += 1

            self._cur_buy_data = None

        counts = [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
        for i, r in enumerate(temp_results):
            if i == 0:
                continue

            is_same = False
            for j, n in enumerate(r.results):
                is_same = False
                if counts[j][0] == -1:
                    continue
                if counts[j][0] >= self._hit_times:
                    continue
                if n >= 5 and temp_result.results[j] >= 5:
                    is_same = True
                    counts[j][1] = 1
                elif n < 5 and temp_result.results[j] < 5:
                    is_same = True
                    counts[j][1] = -1
                else:
                    counts[j][0] = -1

                if is_same:
                    counts[j][0] += 1

            for c in counts:
                if c[0] != -1 and c[0] < self._hit_times:
                    break
                if c[0] >= self._hit_times:
                    is_catch = True

            if is_catch:
                break

        if is_catch:
            buy_data = BuyRoundData()
            self._cur_buy_data = buy_data
            buy_data.round = "x"
            buy_data.pre_round = temp_result.round
            self._buy_list.insert(0, buy_data)
            for i, c in enumerate(counts):
                if c[0] == -1:
                    buy_data.select_nums[i] = []
                else:
                    if c[1] == 1:
                        if self._follow_type == ORDER_FOLLOW:
                            buy_data.select_nums[i] = [5,6,7,8,9]
                        else:
                            buy_data.select_nums[i] = [0,1,2,3,4]
                    else:
                        if self._follow_type == ORDER_FOLLOW:
                            buy_data.select_nums[i] = [0,1,2,3,4]
                        else:
                            buy_data.select_nums[i] = [5,6,7,8,9]
                    if self._stargery_type == STRAGERY_SQUARE:
                        buy_data.pre_money_list[i] = 2**(self._follow_times_list[i]-1)*self._pre_money
                    else:
                        buy_data.pre_money_list[i] = self._follow_times_list[i]*self._pre_money*1
                        
                    round_pay = buy_data.pre_money_list[i]*5
                    if round_pay > self._round_max_pay:
                        self._round_max_pay = round_pay
                    self._my_money -= round_pay
                    if self._my_money < self._min_money:
                        self._min_money = self._my_money

            self._round_max += 1


        for i, r in enumerate(self._buy_list):
            if i >= self._table_record.rowCount():
                break
            table_widget = QtGui.QTableWidgetItem(r.round)
            self._table_record.setItem(i, 0, table_widget)
            table_widget = QtGui.QTableWidgetItem(",".join(map(str, r.select_nums)))
            self._table_record.setItem(i, 1, table_widget)
            table_widget = QtGui.QTableWidgetItem(",".join(map(str, r.results)))
            self._table_record.setItem(i, 2, table_widget)
            table_widget = QtGui.QTableWidgetItem(",".join(map(str, r.hits)))
            table_widget.setTextColor(QtGui.QColor("red"))
            self._table_record.setItem(i, 3, table_widget)
            pass

        self._update_money()
        self._update_summary()

    def _update_money(self):
        self._edit_money.setText(str(self._my_money))

    def _update_summary(self):
        self._table_item_max_round.setText(str(self._round_max))
        self._table_item_max.setText(str(self._max_money))
        self._table_item_min.setText(str(self._min_money))
        if self._max_buy_times > 0:
            self._table_item_percent.setText(
                str(float(self._hit_buy_times*100/self._max_buy_times))
            )
        else:
            self._table_item_percent.setText("0")

        self._table_item_round_max_pay.setText(str(self._round_max_pay))

    def _on_start(self):

        self._running = not self._running
        if self._running:
            self._follow_type = int(self._cb_condition.itemData(
                self._cb_condition.currentIndex()
            ).toString())
            self._stargery_type = int(self._cb_strategy.itemData(
                self._cb_strategy.currentIndex()
            ).toString())
            self._my_money = float(self._edit_money.text())
            self._pre_money = int(self._edit_number_money.text())
            self._hit_times = int(self._edit_hit.text())

            self._timer.start(1)
            self._on_timer()
            self._button_start.setText("暂停")
        else:
            self._button_start.setText("开始")
            self._timer.stop()

    def _stop(self):
        self._button_start.setText("开始")
        self._timer.stop()
        self._running = False

    def _on_reset(self):
        self._stop()

        self._reset_data()
        self._update_money()
        self._update_summary()

